package it.antonio.ilpizze.te.token;

import it.antonio.ilpizze.reflection.MethodAccessor;
import it.antonio.ilpizze.te.Filter;
import it.antonio.ilpizze.te.util.ValueExtractor;

import java.util.Map;

public class InvertedCommandRenderCommand extends NodeRenderCommand{

	private String name;
	private String property;
	private String filterName;
	
	public InvertedCommandRenderCommand(NodeRenderCommand parent, String name, String property, String filterName) {
		super(parent);
		this.name = name;
		this.property = property;
		this.filterName = filterName;
	}


	@Override
	public void contribute(Map<String, Object> model, Map<String, Filter> filters, StringBuffer buffer) {
		Object obj = model.get(name); 
		if(obj != null && property != null) {
			MethodAccessor method = ValueExtractor.getter(obj.getClass(), property);
			obj = method.invoke(obj);	
		}
		
		// BOOLEAN
		if(obj instanceof Boolean){
			boolean b = (Boolean) obj;
			Filter f = filters.get(filterName);
			if(f != null){
				b = (Boolean) f.filter(b);
			} 
			
			if(b == false){
				contributeChildren(model, filters, buffer);
			}
			return;
		}
		
		// ITERABLE
		if(obj instanceof Iterable){
			Iterable<?> it = (Iterable<?>) obj;
			
			Filter f = filters.get(filterName);
			if(f != null){
				it = (Iterable<?>) f.filter(it);
			} 
			
			if(it.iterator().hasNext() == false){
				contributeChildren(model, filters, buffer);
			}
			return;	
		}
		
		// OBJECT
		Filter f = filters.get(filterName);
		if(f != null){
			obj = f.filter(obj);
		} 
		
		if(obj == null){
			contributeChildren(model, filters, buffer);
		}
		
	}
}
